﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Reflection;
using CSW.Framework.Common.Data;

namespace CSW.Framework.Linq
{
    internal class InsertQuery
    {
        private readonly string m_DataProvider;
        private readonly string m_Sql;
        private readonly bool m_HasIdentity;
        private readonly Dictionary<SqlParameter, string/*property name*/> m_Parameters;
        private readonly Dictionary<string, MethodInfo> m_GetterDictionary;

        public InsertQuery(string dataProvider, string sql, bool hasIdentity, Dictionary<SqlParameter, string/*property name*/> parameters, Dictionary<string, MethodInfo> getterDictionary)
        {
            m_DataProvider = dataProvider;
            m_Sql = sql;
            m_HasIdentity = hasIdentity;
            m_Parameters = parameters;
            m_GetterDictionary = getterDictionary;
        }

        public string Sql
        {
            get { return m_Sql; }
        }

        public bool HasIdentity
        {
            get { return m_HasIdentity; }
        }

        public DbParameter[] GetSqlParameters(IBusinessObjectLinq businessObject)
        {
            if (businessObject == null)
                throw new ArgumentNullException("businessObject", "Parameter 'businessObject' cannot be null.");

            DbParameter[] p = new DbParameter[m_Parameters.Count];
            int i = 0;
            foreach (KeyValuePair<SqlParameter, string> kvp in m_Parameters)
            {
                SqlParameter param = kvp.Key;

                object value = m_GetterDictionary[kvp.Value].Invoke(businessObject, null) ?? DBNull.Value;
                p[i] = DataHelper.GetDbParameter(m_DataProvider, param.ParameterName, param.SqlDbType, value);

                i++;
            }

            return p;
        }
    }
}
